<?php
namespace app\api\controller\user;

use app\BaseController;
use app\Request;
use learn\services\UtilService as Util;
use think\facade\Db;

// 引入库
use app\models\user\LoanCollection;             //用户产品收藏表
use app\models\user\LoanBrowse;                 //用户浏览表
use app\models\system\SystemGroupData;          //组合数据
use app\models\user\User;                       //用户表
use app\models\user\UserBasic;                  //用户基本信息
use app\models\user\UserDefinite;               //用户操作
use learn\baidu\BaiduShow;
use think\facade\Env;

class UserController extends BaseController
{
    //用户信息
    public function info (Request $request) 
    {
        $uid = $request->uid();
        $userInfo = User::alias("u")->leftJoin("wechat_user w","w.uid = u.uid")
        ->where("u.uid",$uid)->field("u.*,w.avatar as avatar,w.nickname")->find();

        if ($userInfo) {
            $userInfo = $userInfo->toArray();
            $userBasic = UserBasic::where("uid",$uid)->find();
            if ($userBasic) {
                $userBasic = $userBasic->toArray();
                $userInfo['marriage']           = $userBasic['marriage'];
                $userInfo['address']            = $userBasic['address'];
                $userInfo['detail_address']     = $userBasic['detail_address'];
                $userInfo['education']          = $userBasic['education'];
                $userInfo['company_name']       = $userBasic['company_name'];
                $userInfo['company_address']    = $userBasic['company_address'];
                $userInfo['company_detail_address'] =$userBasic['company_detail_address'];
                $userInfo['card_portrait']      = $userBasic['card_portrait'];
                $userInfo['card_national']      = $userBasic['card_national'];
                $userInfo['license_positive']   = $userBasic['license_positive'];
                $userInfo['license_side']       = $userBasic['license_side'];
                $userInfo['room']               = $userBasic['room'];
                $userInfo['insurance']          = $userBasic['insurance'];
            }else{
                $userInfo['marriage']           = 0;
                $userInfo['address']            = "";
                $userInfo['detail_address']     = "";
                $userInfo['education']          = 0;
                $userInfo['company_name']       = "";
                $userInfo['company_address']    = 0;
                $userInfo['company_detail_address'] = 0;
                $userInfo['card_portrait']      = 0;
                $userInfo['card_national']      = 0;
                $userInfo['license_positive']   = 0;
                $userInfo['license_side']       = 0;
                $userInfo['room']               = 0;
                $userInfo['insurance']          = 0;
            }

        } 
        
        return app("json")->success($userInfo);

    }

    //个人中心
    public function personal (Request $request) 
    {
        //个人中心菜单
        $menu = SystemGroupData::getAllValue("personal_menu");

        //个人中心  --   中间菜单
        $middle = array();
        //个人中心 -- 底部菜单
        $bottom = array();

        foreach($menu as $v) {
            if ($v['type'] == 2) {
                unset($v['type']);
                $middle[] = $v;
            }else if($v['type'] == 3) {
                unset($v['type']);
                $bottom[] = $v;
            }
        }


        return app("json")->success(compact('middle',"bottom"));
    }


    /**
     * 信用档案信息提交
     * type   1 实名认证   2基本信息     3补充信息  4提额信息  5收款卡信息  6 上传基本信息
    */
    public function submit (Request $request)
    {
        $data = Util::postMore([
            ['type',0],                 //提交类型类型    
            ['card_portrait',''],       //身份证人面像
            ['card_national',""],       //身份证国徽

            ['marriage',0],             //婚姻状况
            ['address',""],             //住宅地址
            ['detail_address',""],      //详细地址
            ['education',0],            //学历
            ['company_name',""],        //公司名称
            ['company_address',""],     //公司地址
            ['company_detail_address',""],  //公司详细地址

            ['monthly_income',0],       //月收入
            ['accumulation',0],         //公积金
            ['occupation',0],           //职业类型
            ['company_phone',""],       //公司电话
            ['industry',0],             //行业
            ['borrowing',0],            //借款理由
            ['liabilities',0],          //负债情况

            ['job_time',0],             //在职时间
            ['company_type',0],         //单位类型
            ['residence_info',0],       //住宅情况
            ['add_job_time',0],         //入职时间
            ['post_level',0],           //职务级别
            ['income_source',0],        //收入类型
            ['social_security',0],      //社保




            ['license_positive',""],    //行驶证正面
            ['license_side',""],        //行驶证反面
            ['license_list',''],
            ['room',0],                //有房凭证
            ['insurance',0],           //保单凭证

            ['bank_phone',0],           //银行卡预留手机号
            ['bank_card',""],           //银行卡号

            ['realname',""],            //真实姓名
            ['id_card',""]              //身份证号

        ]);
        $uid = $request->uid();
        if($data['type'] == 0) return app("json")->fail("请选择上传类型");
        $useinfo = User::where("uid",$uid)->find()->toArray();
        $userBasic = UserBasic::where("uid",$uid)->find();

        switch ((int)$data['type']) {
            case 1:

                //实名认证
                if($data['card_portrait'] == "") return app("json")->fail("请上传身份证人面像");
                if($data['card_national'] == "") return app("json")->fail("请上传身份证国徽");
                //验证
                $result = BaiduShow::idcard(app()->getRootPath() . 'public/'.$data['card_portrait'],"front");

                $result1 = BaiduShow::idcard(app()->getRootPath() . 'public/'.$data['card_national'],"back");

                if ($result1['image_status'] != "normal") {
                    unlink(app()->getRootPath() . 'public/'.$data['card_portrait']);
                    unlink(app()->getRootPath() . 'public/'.$data['card_national']);
                    return app("json")->fail($result1["image_status"]);
                }else{
                    $beOverdue = substr($result1['words_result']["失效日期"]['words'],0,4).'-'.substr($result1['words_result']["失效日期"]['words'],4,2).'-'.substr($result1['words_result']["失效日期"]['words'],6);

                    if (strtotime($beOverdue)<time()) {
                        unlink(app()->getRootPath() . 'public/'.$data['card_portrait']);
                        unlink(app()->getRootPath() . 'public/'.$data['card_national']);
                        return app("json")->fail('身份证过期');
                    }
                }

                if ($result['image_status'] != "normal") {
                    unlink(app()->getRootPath() . 'public/'.$data['card_portrait']);
                    unlink(app()->getRootPath() . 'public/'.$data['card_national']);
                    return app("json")->fail($result["image_status"]);
                }

                if ($userBasic) {
                    $res = UserBasic::update(['card_portrait'=>$data['card_portrait'],'card_national'=>$data['card_national']],['uid'=>$uid]);
                }else{
                    $res = UserBasic::create(['card_portrait'=>$data['card_portrait'],'card_national'=>$data['card_national'],'uid'=>$uid]);
                }
                $a = 1;
                $b = 2;
                $c = 3;
                $d = 4;
                $n = 1;
                if ($res) {
                    if ($useinfo['authentication'] == "") {
                        $useinfo['authentication'] = "1";
                    }else{
                        $useinfo['authentication'] .= ",1";
                    }
                    User::where("uid",$useinfo['uid'])->update(['authentication'=>$useinfo['authentication'],'id_card'=>$result['words_result']['公民身份号码']['words'],'realname'=>$result['words_result']['姓名']['words']]);
                    return app("json")->success("提交成功");
                }else{
                    unlink(app()->getRootPath() . 'public/'.$data['card_portrait']);
                    unlink(app()->getRootPath() . 'public/'.$data['card_national']);
                    return app("json")->fail("提交失败");
                }
                
                break;
            case 2:
                //基本信息
                if ($data['marriage'] == 0) return app("json")->fail("请选择婚姻状况");
                if ($data['address'] == "") return app("json")->fail("请选择住宅地址");
                if ($data['detail_address'] == "") return app("json")->fail("请输入详细地址");
                if ($data['education'] == "") return app("json")->fail("请选择学历");
                if ($data['company_name'] == "") return app("json")->fail("请输入公司名称");
                if ($data['company_address'] == "") return app("json")->fail("请选择公司地址");
                if ($data['company_detail_address'] == "") return app("json")->fail("请输入公司详细地址");
                if ($userBasic) {
                    $res = UserBasic::update(['marriage'=>$data['marriage'],'address'=>$data['address'],"detail_address"=>$data['detail_address'],"education"=>$data['education'],"company_name"=>$data['company_name'],"company_address"=>$data['company_address'],"company_detail_address"=>$data['company_detail_address']],['uid'=>$uid]);
                }else{
                    $res = UserBasic::create(['marriage'=>$data['marriage'],'address'=>$data['address'],"detail_address"=>$data['detail_address'],"education"=>$data['education'],"company_name"=>$data['company_name'],"company_address"=>$data['company_address'],"company_detail_address"=>$data['company_detail_address'],'uid'=>$uid]);
                }
                
                if ($useinfo['authentication'] == "") {
                    $useinfo['authentication'] = "2";
                }else{
                    $useinfo['authentication'] .= ",2";
                }
                USer::where("uid",$useinfo['uid'])->update(['authentication'=>$useinfo['authentication']]);
                
                return $res ? app("json")->success("提交成功") : app("json")->fail("提交失败");
                break;
            case 3:
                //补充信息
                $supplement = [
                    "monthly_income"=>$data['monthly_income'],
                    "accumulation"=>$data['accumulation'],
                    "occupation"=>$data['occupation'],
                    "company_phone"=>$data['company_phone'],
                    "industry"=>$data['industry'],
                    "borrowing"=>$data['borrowing'],
                    "liabilities"=>$data['liabilities'],

                    'job_time'=>$data['job_time'],
                    'company_type' => $data['company_type'],
                    'residence_info'=>$data['residence_info'],
                    'add_job_time' =>$data['add_job_time'],
                    'post_level' => $data['post_level'],
                    'income_source' => $data['income_source'],
                    'social_security' => $data['social_security']
                ];
                if ($useinfo['authentication'] == "") {
                    $supplement['authentication'] = "3";
                }else{
                    $supplement['authentication'] = ",3";
                }
                $res = User::where("uid",$uid)->update($supplement);
                return $res ? app("json")->success("提交成功") : app("json")->fail("提交失败");
                break;
            case 4:
                if ($data['license_positive'] == "") return app("json")->fail("请上传行驶证正面");
                if ($data['license_side'] == "") return app("json")->fail("请上传行驶证反面");

                if ($data['license_list'] != "") {
                    $data['jsonList'] = json_decode($data['license_list'],true);
//                    if (User::where("realname",$data['jsonList']['all'])->find()) {
//
//                    }else{
//                        return app("json")->fail("汽车归属人不是本人");
//                    }
                }else{
                    return app("json")->fail("请上传行驶证信息");
                }

                $Withdrawal = [
                    "license_positive"=>$data['license_positive'],
                    "license_side"=>$data['license_side'],
                    "room"=>(int)$data['room'],
                    "insurance"=>(int)$data['insurance'],
                ];

                if ($userBasic) {
                    $res = UserBasic::where("uid",$uid)->update($Withdrawal);
                }else{
                    $Withdrawal['uid'] = $uid;
                    $res = UserBasic::create($Withdrawal);
                }
                if ($res) {
                    if($useinfo['authentication'] == "") {
                        $useinfo['authentication'] = "4";
                    }else{
                        $useinfo['authentication'] .= ",4";
                    }
                    User::where("uid",$uid)->update(['authentication'=>$useinfo['authentication']]);
                    return  app("json")->success("提交成功");
                }else{
                    unlink(app()->getRootPath() . 'public/'.$data['license_positive']);
                    unlink(app()->getRootPath() . 'public/'.$data['license_side']);
                    return app("json")->fail("提交失败");
                }

                break;
            case 5:
                if ($data['bank_phone'] == 0) return app("json")->fail("请输入银行卡预留手机号");
                if ($data['bank_card'] == '') return app("json")->fail("请输入银行卡号");
                $bank = [
                    "bank_phone" => (int)$data['bank_phone'],
                    "bank_card" => $data['bank_card']
                ];
                $res = User::where("uid",$uid)->update($bank);
                return $res ? app("json")->success("提交成功") : app("json")->fail("提交失败");
                break;
            case 6:
                if ($data['realname'] == "") return app("json")->fail(" ");
                if ($data['id_card'] == "") return app("json")->fail("请输入身份证号");
                $basic = [
                    "realname" => $data['realname'],
                    "id_card"  => $data['id_card']
                ];
                $res = User::where(  "uid",$uid)->update($basic);
                return $res ? app("json")->success("提交成功") : app("json")->fail("提交失败");
                break;
            default:
                return app("json")->fail("参数错误");
                break;
                
        }
    }

    /**
     * 用户收藏列表
     */
    public function CollectionList(Request $request)
    {
        $where = Util::postMore([
            ['page',1],
            ['limit',20]
        ]);
        $uid = $request->uid();
        $list = LoanCollection::pageList($where,$uid);
        return app("json")->success(compact("list"));
    }


    /**
     * 添加收藏接口
     */
    public function Collection(Request $request)
    {
        list($id) = Util::postMore([['id',0]],$request, true);
        if ($id == 0) return app("json")->fail("产品不存在");
        $uid = $request->uid();
        $collect = LoanCollection::where("loan_id",$id)->where("uid",$uid)->count();
        if ($collect>0) return  app("json")->fail("产品已收藏");

        $res = LoanCollection::create(['uid'=>$uid,"loan_id"=>$id,"create_time"=>time()]);

        return $res ? app("json")->success("收藏成功") : app("json")->fail("收藏失败");
    }

    /**
     * 浏览列表
     */
    
    public function browseList(Request $request)
    {
        $where = Util::postMore([
            ['page',1],
            ['limit',20]
        ]);
        $uid = $request->uid();
        $list = LoanBrowse::pageList($where,$uid);
        return app("json")->success($list);
    }   

    /**
     * 创建浏览
     */

     public function createBrowse(Request $request)
     {
        list($id) = Util::postMore([['id',0]],$request, true);
        if ($id == 0) return app("json")->fail("产品不存在");
        $uid = $request->uid();
        $num = Db::name("loan_browse")->where("loan_id",$id)->where("uid",$uid)->whereDay("create_time")->count();
        if ($num > 0) {
            return app("json")->success("浏览成功");
        }else{
            $res = LoanBrowse::create(['uid'=>$uid,"loan_id"=>$id,"create_time"=>time()]);
            return $res ? app("json")->success("浏览成功") : app("json")->fail("浏览失败");
        }

     }


     /**
      * 金币明细
      */
    public function goldInfo(Request $request)
    {
        $where = Util::postMore([
            ['page',1],
            ['limit',20],
            ['type',0],
            ['pm','']
        ]);
        $uid = $request->uid();
        $list = UserDefinite::pageList($where,$uid);
        return app("json")->success($list);
    }


}
